package com.vaye.im.websocket;

import cn.dev33.satoken.stp.StpUtil;
import com.vaye.common.constant.ImConstant;
import com.vaye.common.utils.RedisUtil;
import com.vaye.common.utils.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import java.util.List;
import java.util.Map;

/**
 * 分类名称
 *
 * @author wangzhiyong
 * @module admin
 * @date 2023年05月31日 下午2:53
 */
@Slf4j
public class WebSocketConfigurator extends ServerEndpointConfig.Configurator{

    private RedisUtil redisUtil = SpringContextUtils.getBean(RedisUtil.class);

    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        Map<String, Object> userProperties = sec.getUserProperties();
        Map<String, List<String>> headers = request.getHeaders();
        //通过headers参数[Sec-WebSocket-Protocol]获取token值
//        if (!headers.containsKey("Sec-WebSocket-Protocol")) {
//            log.error("the params of token is null");
//            throw new IllegalArgumentException("the params of token is null");
//        }
//        String token = headers.get("Sec-WebSocket-Protocol").get(0);
        String token = headers.get("token").get(0);
        Object loginIdByToken = StpUtil.getLoginIdByToken(token);
        if (ObjectUtils.isEmpty(loginIdByToken)) {
            log.error("用户身份认证失败，握手异常");
            throw new IllegalArgumentException("用户身份认证失败，握手异常");
        }
        Long loginId = Long.valueOf(loginIdByToken + "");
        //用户身份存在，将用户的信息放入session中
        userProperties.put(ImConstant.LOGINID,loginId);
        userProperties.put(ImConstant.HOST,headers.containsKey("host")?headers.get("host").get(0):"unknowIp");
        //响应的时候还要把[Sec-WebSocket-Protocol]原封不动的返回给前端，不然的话会报错
//        response.getHeaders().put("Sec-WebSocket-Protocol",headers.get("Sec-WebSocket-Protocol"));
    }
}
